package com.lolineet.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lolineet.entity.user.SysMenu;
import com.lolineet.user.mapper.SysMenuMapper;
import com.lolineet.user.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lolineet
 * @since 2025-04-17
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> getMenuList() {
        List<SysMenu> list = sysMenuMapper.selectList(new LambdaQueryWrapper<>());

        Map<Long, List<SysMenu>> parentMap = list.stream()
                .collect(Collectors.groupingBy(SysMenu::getParentId));
        /*递归设置子节点*/
        list.stream().filter(item -> item.getParentId() == 0)
                .forEach(item -> setChildrenList(item, parentMap));
        list= list.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        return list;
    }

    void setChildrenList(SysMenu menu, Map<Long, List<SysMenu>> parentMap) {
        List<SysMenu> childList = parentMap.get(menu.getId());
        if (childList != null) {
            childList.stream().forEach(item -> {
                if (parentMap.get(item.getId()) != null) {
                    setChildrenList(item, parentMap);
                }
            });
            menu.setChildrenMenuList(childList);
        }
    }

}
